<template>
  <!-- 问题三 -->
  <a-modal
    title="录入订单"
    :width="1200"
    :visible="visible"
    destroyOnClose
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="主键"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入主键"
                       v-decorator="['orderId', {rules: [{required: false, message: '请输入主键！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="父订单"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入父订单"
                       v-decorator="['orderPids', {rules: [{required: false, message: '请输入父订单pids！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="生产单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input
                placeholder="请输入生产单号"
                v-decorator="['orderNumber', {rules: [{required: true, message: '请输入生产单号'}]}]"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="关联订单"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入父订单"
                       v-decorator="['orderParentId', {rules: [{required: false, message: '请输入父订单！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="国家"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-select
                @focus="getguojia"
                placeholder="请选择"
                style="width: 272px"
                v-decorator="['countryCode', {rules: [{required: true, message: '请选择国家！'}]}]"
              >
                <a-select-option :value="item.id" v-for="(item, index) in guojiaList" :key="index">{{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="下发时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入下发时间" v-decorator="['issueTime', {rules: [{required: true, message: '请输入下发时间！'}]}]"/>-->
              <a-date-picker placeholder="请输入下发时间"
                             v-decorator="['issueTime', {rules: [{required: true, message: '请输入下发时间！'}]}]"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
                             :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="预计完成时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入预计完成时间" v-decorator="['estimateCompletionTime', {rules: [{required: true, message: '请输入预计完成时间！'}]}]"/>-->
              <a-date-picker placeholder="请输入预计完成时间"
                             v-decorator="['estimateCompletionTime', {rules: [{required: true, message: '请输入预计完成时间！'}]}]"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
                             :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="订单类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入订单类型" v-decorator="['orderType', {rules: [{required: true, message: '请输入订单类型！'}]}]"/>-->
              <a-select placeholder="请输入订单类型"
                        v-decorator="['orderType', {rules: [{required: true, message: '请输入订单类型！'}]}]">
                <a-select-option :value="item.id" v-for="(item, index) in orderTypeList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="归属子公司"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-select placeholder="请输入归属子公司"
                        v-decorator="['targetOrgId', {rules: [{required: true, message: '请输入归属子公司！'}],}]">
                <a-select-option :value="id" v-for="{id, name} in companyList" :key="id">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="是否是海外仓"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入是否是海外仓" v-decorator="['isOverseasStore', {rules: [{required: true, message: '请输入是否是海外仓！'}]}]"/>-->
              <a-select placeholder="请输入是否是海外仓"
                        v-decorator="['isOverseasStore', {rules: [{required: true, message: '请输入是否是海外仓！'}],initialValue:'N'}]"
              >
                <a-select-option value="Y">是</a-select-option>
                <a-select-option value="N">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="接收时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入接收时间" v-decorator="['receiveTime', {rules: [{required: true, message: '请输入接收时间！'}]}]"/>-->
              <a-date-picker placeholder="请输入接收时间"
                             v-decorator="['receiveTime', {rules: [{required: true, message: '请输入接收时间！'}]}]"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
                             :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="排序"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input-number
							style="width: 100%;"
                placeholder="请输入排序"
								:min="0"
                v-decorator="['sort', {rules: [{required: true, message: '请输入排序！'}]}]"           
              />              
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="附件"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <a-input
                placeholder="请上传附件"
                v-decorator="['file', {rules: [{required: true, message: '请上传附件！'}]}]"
                v-show="false"
              />
              <fc-upload :file-list="fileList" :handle-file-list-string-change="handleFileListStringChange"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="24">
            <a-form-item
              v-if="form.getFieldValue('file')"
              label="预览"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <!-- <a>{{form.getFieldValue('file')}}</a> -->
              <a target="_blank" :href="`${$store.state.baseUrl}/sysFileInfo/preview?id=${form.getFieldValue('file')}`">下载
                / 预览</a>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback>
              <!-- <a-input placeholder="请输入备注" v-decorator="['remark', {rules: [{required: true, message: '请输入备注！'}]}]"
                       type="textarea"/> -->
              <antd-editor
                ref="md"
                :uploadConfig="editorUploadConfig"
                v-model="remark"
                @onchange="changeEditor"
                @oninit="getEditor"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="进度状态"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入进度状态"
                       v-decorator="['progressStatus', {rules: [{required: true, message: '请输入进度状态！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="生产进度"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入生产进度"
                       v-decorator="['produceProgress', {rules: [{required: true, message: '请输入生产进度！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="状态（字典 0正常 1冻结 2删除）"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入状态（字典 0正常 1冻结 2删除）"
                       v-decorator="['status', {rules: [{required: true, message: '请输入状态（字典 0正常 1冻结 2删除）！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="创建时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入创建时间"
                       v-decorator="['createTime', {rules: [{required: true, message: '请输入创建时间！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="创建人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入创建人"
                       v-decorator="['createUser', {rules: [{required: true, message: '请输入创建人！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="更新时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入更新时间"
                       v-decorator="['updateTime', {rules: [{required: true, message: '请输入更新时间！'}]}]"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="更新人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入更新人"
                       v-decorator="['updateUser', {rules: [{required: true, message: '请输入更新人！'}]}]"/>
            </a-form-item>
          </a-col>
        
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {add, addAllType} from '@/api/modular/main/emsorder/emsOrderManage'
import FcUpload from '@/components/FCUpload/FcUploadPDF'
import moment from 'moment'
import {ORDER_TYPE_ENUM} from '@/utils/util'
import {sysFileInfoUpload} from '@/api/modular/system/fileManage'
import {getOrgTree} from '@/api/modular/system/orgManage'
import {AntdEditor} from '@/components'

export default {
  components: {
    FcUpload,
    AntdEditor
  },
  computed: {
    orderTypeList() {
      let result = []
      for (const key in ORDER_TYPE_ENUM) {
        let value = ORDER_TYPE_ENUM[key]
        result.push(value)
      }
      return result
    },
    companyList() {
      return this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id])
    }
  },
  props: {
    // -----------------------修改apiTest-------------------------------
    action: {
      type: String,
      default: '/api/sysFileInfo/upload'
    },
  },
  data() {
    return {
      
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 3}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
      editorUploadConfig: {
        method: 'http',
        callback: this.editorUploadImage
      },
      editor: '',
      remark: '',
      guojiaList: [],
      editorContentText: '',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      sysOrgs: [],
      fileList: [],
      orgTree: [],
    }
  },
  methods: {
    moment,
    add(record) {
      this.visible = true
      // record.isOverseasStore = 'N'
      this.fileList = []
      // 设定订单类型
      setTimeout(() => {
        this.form.setFieldsValue(record)
        this.createOrderNumber()
      }, 100)
    },
    fcsuccess(url) {
      this.form.setFieldsValue({image: url})
    },
    // 打开弹框时候生成一个单号
    createOrderNumber() {
      var d = new Date()
      var year = d.getFullYear()
      var month = d.getMonth()
      month = month + 1 > 12 ? 1 : month + 1
      month = month > 9 ? month : "0" + month.toString()
      var day = d.getDate()
      day = day > 9 ? day : "0" + day.toString()
      var hour = d.getHours()
      hour = hour > 9 ? hour : "0" + hour.toString()
      var minute = d.getMinutes()
      minute = minute > 9 ? minute : "0" + minute.toString()
      var second = d.getSeconds()
      second = second > 9 ? second : "0" + second.toString()
      
      let num = parseInt(Math.random() * 100000).toString()
      // 如果随机数长度不够5位,则在后面补0,够5位为止
      for (let i = num.length; i < 5; i++) {
        num += '0'
      }
      
      let scOrderNo = 'SC' + year + month + day + hour + minute + second + num
      
      this.form.setFieldsValue({orderNumber: scOrderNo})
    },
    
    handleSubmit() {
      
      const {form: {validateFields}} = this
      
      validateFields((errors, values) => {
        
        
        if (!errors) {
          if (this.remark == '') {
            this.$message.error("请输入备注")
            return
          }
          let _values = Object.assign({}, values)
          const timeKeys = ['receiveTime', 'estimateCompletionTime', 'issueTime']
          timeKeys.forEach(key => {
            let value = _values[key]
            console.log('value', value)
            _values[key] = typeof value === 'object' ? value.format('YYYY-MM-DD HH:mm:ss') : value
          })
          console.log(values)
          
          this.confirmLoading = true
          
          addAllType({remark: this.remark, ..._values}).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('新增成功')
              this.$emit('ok', values)
              this.handleCancel()
              
            } else {
              this.$message.info('新增失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        }
      })
    },
    getguojia() {
      this.axios.get('/sysDictData/list?typeCode=COUNTRY').then((res) => {
        this.guojiaList = res.data
      })
    },
    getEditor(editor) {
      this.editor = editor
    },
    changeEditor(html, ele) {
      this.remark = html
      this.editorContentText = ele.text()
    },
    // 富文本
    editorUploadImage(files, insert) {
      const formData = new FormData()
      files.forEach(file => {
        formData.append('file', file)
      })
      sysFileInfoUpload(formData).then((res) => {
        if (res.success) {
          insert(process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + res.data)
        } else {
          this.$message.error('编辑器上传图片失败：' + res.message)
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.remark = ''
      this.editor = ''
      this.editorContentText = ''
      this.visible = false
      this.$refs.md?.wangEditor?.txt?.clear()
    },
    // upload
    handleFileListStringChange(fileListString) {
      this.form.setFieldsValue({file: fileListString})
    },
    getOrgTree() {
      getOrgTree().then((res) => {
        this.formLoading = false
        if (!res.success) {
          this.orgTree = []
          return
        }
        this.orgTree = [{
          'id': '-1',
          'parentId': '0',
          'title': '顶级',
          'value': '0',
          'pid': '0',
          'children': res.data
        }]
      })
    }
  }
}
</script>
